<template>
  <el-container direction="vertical">
    <el-header>
      <h3>角色管理</h3>
    </el-header>
    
    <el-main>
      <div class="block-wrap" v-loading="loading">
        <div class="header">
          <el-button icon="el-icon-plus" class="margin-b-15" type="primary" size="small" @click="showDialog('add')">添加角色</el-button>
          <el-input class="width310 margin-b-15" v-model="searchForm.keyword" clearable placeholder="请输入关键字搜索" size="small">
            <el-button slot="append" @click="getRoleList(true)"><i class="el-icon-search"></i>&nbsp;搜索</el-button>
          </el-input>
        </div>
        <el-table :data="tableData" stripe center border>
          <el-table-column prop="name" label="名称">
          </el-table-column>
          <el-table-column prop="is_platform" label="是否平台管理员">
            <template slot-scope="scope">{{scope.row.is_platform == 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="is_department" label="是否部门管理员">
            <template slot-scope="scope">{{scope.row.is_department == 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="number" label="角色数量">
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="showDialog('edit', scope.row.role_id)">编辑</el-button>
              <el-button type="text" size="small" @click="deleteRole(scope.row.role_id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="margin-t-15"
          :current-page="$store.state.pagination.pageNum"
          :page-sizes="[20, 40, 80, 100]"
          :page-size="20"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total" background>
        </el-pagination>
      </div>
      <!-- 弹框 -->
      <el-dialog :title="tempOperateType == 'add' ? '添加角色' : '编辑角色'" :visible.sync="dialogRoleVisible" width="534px" :close-on-click-modal="false">
        <el-form :model="roleForm" :rules="roleFormRules" ref="roleForm" label-width="120px" label-suffix="：">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model.trim="roleForm.name" autocomplete="off" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="平台管理员" prop="is_platform">
            <el-radio-group v-model="roleForm.is_platform">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="部门管理员" prop="is_department">
            <el-radio-group v-model="roleForm.is_department">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="权限分配" prop="treeNodes">
            <el-tree
              class="permission-tree"
              ref="authorityTree"
              :data="authorityTree"
              :props="defaultProps"
              node-key="id"
              default-expand-all
              show-checkbox>
            </el-tree>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer align-center">
          <el-button @click="dialogRoleVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
  export default {
    data () {
      return {
        loading: false,
        tempOperateType: 'add',
        tableData:[],
        formLabelWidth:'150px',
        dialogRoleVisible: false,
        searchForm: {
          keyword: ''
        },
        authorityTree: [], // 权限树
        total: 0,

        roleForm:{
          name:          null,
          is_platform:   2,
          is_department: 2,
          treeNodes:     [],
        },
        roleFormRules: {
          name:          [{required: true, type: 'string', message: '请输入角色名称'}],
          is_platform:   [{required: true, message: '请选择类型'}],
          is_department: [{required: true, message: '请选择类型'}],
        },
        defaultProps: {
          children: 'children_list',
          label: 'action'
        }
      }
    },
    mounted() {
      this.getRoleList(true)
      this.getAuthorityTree()
    },
    methods: {
      /**
       * 分页控制器
       * @param  {[type]} val [description]
       * @return {[type]}     [description]
       */
      handleCurrentChange(val) {
        this.$store.commit('changePage', val)
        this.getRoleList(false)
      },
      /**
       * 获得所有权限树
       */
      getAuthorityTree(){
        let config = {
          method: "post",
          url: "meeting/role/getAllAction",
        }
        this.loading = true
        this.$axios(config).then(res => {
          this.authorityTree = res.data
          this.loading = false
        }).catch(err => {
          this.$message.error(err.msg)
          this.loading = false
        })
      },
      /**
       * 获取角色列表
       * @param  {[type]} init [description]
       * @return {[type]}      [description]
       */
      getRoleList(init){
        if(init){
          this.$store.commit("changePage", 1)
        }
        let config = {
          method: "post",
          url: "meeting/role/showRole",
          data: this.searchForm
        }
        config.data.p = this.$store.state.pagination.pageNum
        config.data.admin_id = sessionStorage.getItem('admin_id')
        this.loading = true
        this.$axios(config).then(response => {
          this.tableData = response.data.data
          this.total     = response.data.total
          this.$nextTick(_ => {
            this.loading = false
          })
        }).catch(err => {
          this.$message.error(err.msg)
          this.loading = false
        })
      },
      /**
       * 弹出框显示--添加和编辑
       * @param  {[type]} type [description]
       * @param  {[type]} data [description]
       * @return {[type]}      [description]
       */
      showDialog(type,id){
        this.tempOperateType = type
        if(type == "add"){
          this.dialogRoleVisible = true
          this.$nextTick(_ => {
            if(this.$refs.roleForm) {
              this.$refs.roleForm.resetFields()
            }
            this.$refs.authorityTree.setCheckedNodes([])
          })
        }else{
          this.getDetail(id)
        }
      },
      /**
       * 查询角色详情
       * @param  {[type]} id [description]
       * @return {[type]}    [description]
       */
      getDetail(id) {
        let config = {
          method: 'post',
          url: `meeting/role/detailRole`,
          data: {role_id: id}
        }
        this.$axios(config).then(res => {
          this.dialogRoleVisible = true
          this.roleForm = res.data
          let array = res.data.permission ? res.data.permission.split(',') : []
          this.$nextTick(_ => {
            this.$refs.authorityTree.setCheckedKeys(array)
          })
        }).catch(err => {
          this.$message.error(err.msg)
        })
      },
      /**
       * 提交表单
       * @param  {[type]} formName [description]
       * @return {[type]}          [description]
       */
      submitForm(){
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            let config = {
              method: "post",
              url: "",
              data: this.roleForm
            }

            this.roleForm.treeNodes = this.$refs.authorityTree.getCheckedKeys()
            config.data.permission = this.roleForm.treeNodes.join(',')
            delete config.data.treeNodes
            config.data.admin_id = sessionStorage.getItem('admin_id')

            if(this.tempOperateType == "add"){
              config.url = "meeting/role/createRole"
            }else{
              config.url = "meeting/role/editRole"
            }
            this.$axios(config).then(res => {
              this.$message.success(res.msg)
              this.dialogRoleVisible = false
              this.getRoleList(false)
            }).catch(err => {
              this.$message.error(err.msg)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      /**
       * 删除单元
       * @param  {[type]} id [description]
       * @return {[type]}    [description]
       */
      deleteRole(id) {
        this.$confirm('确认删除该角色？', '提示', {type: 'warning'}).then(_ => {
          this.loading = true
          let config = {
            method: 'post',
            url: `meeting/role/deleteRole`,
            data: {role_id: id}
          }
          this.$axios(config).then(res => {
            this.$message.success(res.msg)
            this.getRoleList(true)
            this.loading = false
          }).catch(err => {
            this.$message.error(err.msg)
            this.loading = false
          })
        }).catch(_ => {})
      }
    }
  }
</script>
<style type="text/css" lang="less" scoped>
  .header{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
  .width310{
    width: 310px;
  }
</style>